package com.example.demo.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.Status;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2022-03-30
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping(value = "/login")
    @ResponseBody
    // 登录
    public String login(@RequestBody  User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.eq("account", user.getAccount()).eq("password", user.getPassword());
        return userMapper.selectOne(userQueryWrapper) == null ? JSON.toJSONString(new Status(400,"登录失败")) : JSON.toJSONString(new Status(200,"登录成功"));
    }

    @PostMapping(value = "/register")
    @ResponseBody
    public String register(User user)
    {
        // 先检查数据库是否有这个账号
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("account",user.getAccount());
        User user1 = userMapper.selectOne(userQueryWrapper);
        if (user1 != null)
        {
            return JSON.toJSONString("账号已存在");
        }
        int insert = userMapper.insert(user);
        if (insert == 1)
        {
            return JSON.toJSONString("注册成功");
        }
        return JSON.toJSONString("注册失败");
    }

}

